<template>
	<view class="page">
		<div class="header app-search-wrap shadow">
	<!-- 		<uni-search-bar class="search" cancelButton='none' @confirm="search" :focus="true" v-model="searchValue"
				@blur="blur" @focus="focus" @input="input" @cancel="cancel" @clear="clear">
			</uni-search-bar> -->
			<view class="example-body" style="width: 99%;">
						<uni-datetime-picker
							v-model="range"
							type="daterange"
							:start="startDate"
							:end="endDate"
							rangeSeparator="至"
						/>
					</view>
		</div>

		<uv-empty v-if="!listData.length" mode="list"></uv-empty>

		<view v-for="(item, index) in listData" :key="index">
			<uni-list>

				<uni-list-item link @click="onClick($event,item.id)">
					<template slot="header">
						<view class="contents">
							<text class="title" :class="{'red':item.overDate}">{{item.title}}</text>
							<text class="note">{{item.deptName}}-{{item.operName}}-{{item.operLocation}}</text>
							<text class="note">{{item.operTime}}</text>
						</view>
					</template>
			
				</uni-list-item>
			</uni-list>
		</view>
		<uni-section v-if="listData.length" class="bottom" padding>
			<uni-pagination :total="total" title="标题文字" :current="current" :pageSize="pageSize" @change="getListDate" />
		</uni-section>

	</view>
</template>

<script>
	import {
		log
	} from 'util';
	import {
		baseUrl
	} from '@/config.js';
	import {
		getToken
	} from '@/utils/auth'
	import storage from '@/utils/storage'
	import {
		getLogList as getLists
	} from '@/api/me'
	export default {
		data() {
			return {
				showAdmin: false,
				searchValue: '',
				current: 1,
				total: 0,
				pageSize: 10,
				listData: [],
				globalConfig: getApp().globalData.config,
				range: ["2021-03-8", "2021-4-20"],
				startDate: '',
				endDate: '',
			}
		},
				watch: {

					range(newval) {
						console.log('范围选:', this.range);
						this.getListDate()
					},
				},
		onLoad() {
			this.getListDate();
			let date = this.getFormattedDate();
			let beforDate = this.getOneYearAgoDate();
			this.range = [date, date];
			this.startDate = beforDate;
			this.endDate = date;
			let vuex_roles = storage.get('vuex_roles');
			if (vuex_roles.includes('admin') || vuex_roles.includes('system')) this.showAdmin = true;
			
			
		},
		onShow() {
			this.getListDate();
		},
		methods: {
			 getFormattedDate() {
			    const date = new Date();
			    const year = date.getFullYear();
			    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1，并确保两位数
			    const day = String(date.getDate()).padStart(2, '0'); // 确保日期为两位数
			    return `${year}-${month}-${day}`;
			},
			getOneYearAgoDate() {
			    const today = new Date();
			    const oneYearAgo = new Date(today);
			    oneYearAgo.setFullYear(today.getFullYear() - 1);
			
			    const year = oneYearAgo.getFullYear();
			    const month = String(oneYearAgo.getMonth() + 1).padStart(2, '0');
			    const day = String(oneYearAgo.getDate()).padStart(2, '0');
			
			    return `${year}-${month}-${day}`;
			},
			improtClick(e) {
				let baseUrl = this.globalConfig.baseUrl;
				wx.chooseMessageFile({
					count: 1, // 默认9
					type: 'file', // 可以指定为'all'、'image'、'video'、'audio'、'file'
					success: function(res) {
						const tempFilePaths = res.tempFiles[0].path; // 获取到临时文件路径
						wx.uploadFile({
							url: baseUrl + '/system/equipment/importData', // 服务器接口地址
							header: {
								Authorization: 'Bearer ' + getToken(),
								contentType: "multipart/form-data"
							},
							filePath: tempFilePaths,
							name: 'file', // 对应服务器端接收文件字段名
							formData: {
								// 文件上传额外携带的信息，如用户标识等
								updateSupport: "true"
							},
							success: function(res) {
								debugger
								const data = res.data;
								uni.showToast({
									title: '上传成功',
									icon: "none"

								})
								// 上传成功处理逻辑
							},
							fail: function(err) {
								// 上传失败处理逻辑
							}
						});
					}
				})

			},
			download(file) {
				uni.showLoading({
					title: '下载中'
				});
				wx.downloadFile({
					header: {
						Authorization: 'Bearer ' + getToken()
					},
					url: baseUrl + '/system/equipment/export',
					success: function(res) {
						uni.hideLoading()
						wx.openDocument({
							filePath: res.tempFilePath,
							showMenu: true,
							success: function() {
								console.log('文件打开成功');
							},
							fail: function() {
								console.error('文件打开失败');
							}
						});
					},
					fail: function() {
						console.error('下载文件失败');
					}
				});
				return;
				//下载文件
				uni.downloadFile({ //只能是GET请求
					url: baseUrl + '/system/equipment/export', //请求地址(后台返回的码流地址)
					success: (res) => {
						//下载成功
						if (res.statusCode === 200) {
							//保存文件
							let tempFile = res.tempFilePath;
							//保存成功之后 打开文件
							uni.getFileSystemManager().saveFile({
								tempFilePath: tempFile,
								// filePath: wx.env.USER_DATA_PATH + '/' + '上传成员.pdf',//自定义文件名
								success(res) {
									console.log(res)
									uni.openDocument({
										filePath: res.savedFilePath,
										showMenu: true, //是否可以分享
										success: (res) => {
											uni.hideLoading()
											console.log(res);
										},
										fail: (e) => {
											uni.showToast({
												title: '打开失败',
												icon: "error"
											})
										}
									})

								}
							})
						}
					},
					fail: (e) => {
						console.log(e, '文件下载失败')
						uni.showToast({
							title: '文件下载失败',
							icon: "error",
						})
					}
				});
			},
			getListDate(e) {
				if (e) {
					let {
						type,
						current
					} = e;
					console.log(type, current)
					this.current = current;
				}

				// let res = await getList()
				getLists({
					pageSize: this.pageSize,
					pageNum: this.current,
					searchValue: this.searchValue,
					"params[beginTime]": this.range[0],
					"params[endTime]": this.range[1],
					"beginTime": this.range[1],
					"endTime": this.range[1],
				}).then(res => {
					res.rows.forEach(item => item.noteName = `${item.equipmentModel}(${item.position})`);
					console.log(res)
					this.listData = res.rows;
					this.total = res.total;
				})
			},
		
			onClick(e, id) {
				return false;
				console.log(e, id);
				let ob = this.listData.find(item => item.id === id);
				uni.navigateTo({
					url: `/pages/work/device-detail/index?id=${id}`,
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('acceptDataFromOpenerPage', ob)
					}
				})

			},
			onClickDel(e, id) {
				uni.showModal({
					title: "提示",
					content: "确认删除？",
					success: (res) => {
						if (res.confirm) {
							deleteEq({
								id
							}).then(res => {
								this.getListDate()
								console.log(res.msg)
								uni.showToast({
									title: res.msg,
									duration: 2000
								});
							})
						}
					}
				})

			},
			search(res) {
				uni.showToast({
					title: '搜索：' + res.value,
					icon: 'none'
				})
			},
			input(res) {
				this.searchValue = res;
				this.getListDate()
			},
			clear(res) {
				// uni.showToast({
				// 	title: 'clear事件，清除值为：' + res.value,
				// 	icon: 'none'
				// })
			},
			cancel(res) {
				// uni.showToast({
				// 	title: '点击取消，输入值为：' + res.value,
				// 	icon: 'none'
				// })
			},

		},
		onBackPress() {
			// #ifdef APP-PLUS
			plus.key.hideSoftKeybord();
			// #endif
		}

	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
		padding-top: 110rpx;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-around;

	}

	.btn {
		padding: 20rpx;
		margin: -20rpx -20rpx -20rpx 0;

		&>view {
			@include item-btn($after-color, rgba($after-color, 0.7));
		}
	}

	.btn-add {
		&>view {
			@include item-btn($theme-color, rgba($theme-color, 0.7));
		}
	}

	.btn-del {
		&>view {
			@include item-btn(#f84b4c, rgba(#f84b4c, 0.6));
		}
	}

	.contents {
		display: flex;
		padding-right: 8px;
		flex: 1;
		color: #3b4144;
		flex-direction: column;
		justify-content: space-between;
		overflow: hidden;

		.title {
			font-size: 14px;
			color: #3b4144;
			overflow: hidden;
		}

		.note {
			margin-top: 6rpx;
			color: #999;
			font-size: 12px;
			overflow: hidden;
		}
	}

	.red {
		color: #f84b4c !important;
	}
</style>